import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { UNIFIED_LOGIN_CONFIG } from '@/config'
import { login } from '@/api/auth'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home.vue'),
    meta: { 
      title: '首页',
      requiresAuth: true // 需要登录
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { 
      title: '登录'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

/**
 * 获取当前完整的回调URL
 */
function getCallbackUrl() {
  return window.location.origin + window.location.pathname
}

/**
 * 跳转到统一登录中心
 */
function redirectToLogin(error = '') {
  const callback = encodeURIComponent(getCallbackUrl())
  const loginUrl = `${UNIFIED_LOGIN_CONFIG.loginUrl}?callback=${callback}&app_name=${UNIFIED_LOGIN_CONFIG.appName}&app_id=${UNIFIED_LOGIN_CONFIG.appId}${error ? `&error=${encodeURIComponent(error)}` : ''}`
  console.log('[Router] 跳转到登录中心:', loginUrl)
  window.location.href = loginUrl
}

/**
 * 清理URL中的access_token参数
 */
function cleanUrlParams() {
  const url = new URL(window.location.href)
  url.searchParams.delete('access_token')
  window.history.replaceState({}, '', url.toString())
}

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  console.log('[Router] 路由跳转:', from.path, '->', to.path)
  
  // 设置页面标题
  document.title = to.meta.title || '统一登录Demo'
  
  const userStore = useUserStore()
  
  // 检查URL中是否有access_token（统一登录中心回调）
  const urlParams = new URLSearchParams(window.location.search)
  const accessToken = urlParams.get('access_token')
  
  if (accessToken) {
    console.log('[Router] 检测到access_token，开始认证...')
    
    try {
      // 调用后端认证接口
      const response = await login(accessToken)
      
      if (response.code === 200 && response.data) {
        console.log('[Router] 认证成功')
        
        // 保存用户信息
        userStore.saveAuthInfo(response.data)
        
        // 清理URL中的access_token
        cleanUrlParams()
        
        // 跳转到目标页面
        next({ path: to.path, query: to.query, replace: true })
        return
      } else {
        console.error('[Router] 认证失败:', response.message)
        userStore.clearAuthInfo()
        redirectToLogin(response.message || '认证失败')
        return
      }
    } catch (error) {
      console.error('[Router] 认证异常:', error)
      userStore.clearAuthInfo()
      redirectToLogin('认证服务异常')
      return
    }
  }
  
  // 检查是否需要登录
  if (to.meta.requiresAuth) {
    if (userStore.isLogin && userStore.token) {
      console.log('[Router] 用户已登录，继续访问')
      next()
    } else {
      console.log('[Router] 未登录，跳转到登录中心')
      userStore.clearAuthInfo()
      redirectToLogin('请先登录')
    }
  } else {
    // 不需要登录的页面直接放行
    next()
  }
})

export default router

